package cn.edu.zzuli.springcloud.controller;


import cn.edu.zzuli.springcloud.entities.CommonResult;
import cn.edu.zzuli.springcloud.entities.Payment;
import cn.edu.zzuli.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果->：" + result + "端口号->：" + serverPort);
        if (result > 0) {
            return new CommonResult<Payment>(200, serverPort + "create数据成功",payment);
        }
        return new CommonResult<Payment>(444, "failed");
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果->：" + payment + "端口号->：" + serverPort);

        return new CommonResult<Payment>(200, serverPort + "查询成功",payment);
    }

    @GetMapping("/payment/discovery")
    public Object discoveryClient() {
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            log.info("****element: " + s);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
//        for (ServiceInstance i : instances) {
//            log.info(i.getHost() + "\t" +  + i.getPort() + "\t" + i.getUri());
//        }
        instances.forEach(i -> {
            log.info(i.getHost() + "\t" +  + i.getPort() + "\t" + i.getUri());
        });
        return discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLb() {
        return serverPort;
    }

    @GetMapping("/payment/timeout")
    public String getPaymentTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String zipkin() {
        return "zipkin from cloud-provider-payment8001";
    }

}
